package com.cskaoyan.advice;

import com.cskaoyan.bean.common.BaseRespVo;
import com.cskaoyan.exception.ValidationException;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author 楚夏三分
 * @Description: TODO: 对项目运行中的异常进行处理
 * TODO: 加了@RestControllerAdvice之后, 会自动对项目运行时产生的相应异常进行处理
 * TODO: 如果项目运行时抛出了A异常, 项目并不会直接报错, 而是交给异常处理器进行异常处理
 * @since 2022/12/29 14:34
 */
@RestControllerAdvice
public class ExceptionControllerAdvice {
    // MethodArgumentNotValidException
    // @ExceptionHandler(MethodArgumentNotValidException.class)
    // public BaseRespVo methodArgumentNotValidExceptionResolver(MethodArgumentNotValidException exception) {
    //     return BaseRespVo.invalidParameter("用户名长度需在3-9位之间!");
    // }

    @ExceptionHandler(ValidationException.class)
    public BaseRespVo validationExceptionResolver(ValidationException exception) {
        String message = exception.getMessage();
        return BaseRespVo.invalidParameter(message);
    }

    @ExceptionHandler(InvalidFormatException.class)
    public BaseRespVo invalidFormatExceptionResolver(InvalidFormatException exception) {
        return BaseRespVo.invalidParameter("参数不合格");
    }

    // AuthorizationException

    /**
     * TODO: 新增了未授权的异常处理器
     * @param exception 处理的异常
     * @return
     */
    @ExceptionHandler(AuthorizationException.class)
    public BaseRespVo invalidAuthorizationExceptionResolver(AuthorizationException exception) {
        return BaseRespVo.unAuthor();
    }
}
